import numpy as np
import cv2 as cv
import copy

img = cv.imread(r'C:\Users\Administrator\Desktop\rice.png')

# 转化为灰度图像
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

#使用局部阈值的大津算法进行图像二值化
bw=cv.adaptiveThreshold(gray,255,cv.ADAPTIVE_THRESH_MEAN_C,cv.THRESH_BINARY, 101, 1)
element=cv.getStructuringElement(cv.MORPH_CROSS, (3, 3))
bw=cv.morphologyEx(bw, cv.MORPH_OPEN, element)

seg=copy.deepcopy(bw)
bin, cnts, hier=cv.findContours(seg, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

count=0
area_list=[]
length_list=[]
for i in range(len(cnts),0,-1):
    c=cnts[i-1]
    area=cv.contourArea(c)
    #length=cv.arcLength(c,True)
    if area<10:
        continue
    count=count+1

    x,y,w,h=cv.boundingRect(c)
    cv.rectangle(img,(x,y),(x+w,y+h),(0,0,0xff),1)
    cv.putText(img,str(count),(x,y),cv.FONT_HERSHEY_PLAIN,0.5,(0,0xff,0))
    length = round(np.sqrt(w * w + h * h), 2)
    area_list.append(copy.deepcopy(area))
    length_list.append(copy.deepcopy(length))
    print("blob", i, ":area  ", area, ":length  ", length)
area_mean=np.mean(area_list)
area_var = np.var(area_list)
area_std = np.std(area_list)
# 3sigma范围的数据统计
area_i=0
area_total=0
for area1 in area_list:
    area_total+=1
    if area_mean-3*area_std <= area1 < area_mean+3*area_std:
        area_i+=1

length_mean=np.mean(length_list)
length_var = np.var(length_list)
length_std = np.std(length_list)
# 3sigma范围的数据统计
length_i=0
length_total=0
for length1 in length_list:
    length_total+=1
    if length_mean-3*length_std <= length1 < length_mean+3*length_std:
        length_i+=1

print("米粒数量：",count)
print("面积均值：",area_mean,"  面积方差：",area_var, "面积3sigma范围内数量：",area_i, '面积3sigma范围内比例：{:.2f}%'.format(area_i/area_total*100))
print("长度均值：",length_mean,"  长度方差：",length_var, "长度3sigma范围内数量：",length_i, '长度3sigma范围内比例：{:.2f}%'.format(length_i/length_total*100))
cv.imshow('Source image', img)
cv.imshow('threshold image', bw)


cv.waitKey()
cv.destroyAllWindows()

'''
输出：
采用局部大津算法及开运算进行图像处理
米粒数量： 94

面积均值： 172.64893617021278   
面积方差： 4224.477818017203 
面积3sigma范围内数量： 92 
面积3sigma范围内比例：97.87%


长度均值： 29.3431914893617   
长度方差： 50.466591942055224 
长度3sigma范围内数量： 93 
长度3sigma范围内比例：98.94%

分析：3sigma包含了绝大多数样本，近似高斯分布
'''